package com.lxw.manage.course.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lxw.framework.domain.course.CourseBase;
import com.lxw.framework.domain.course.CoursePic;
import com.lxw.framework.domain.course.Teachplan;
import com.lxw.framework.domain.course.ext.CourseInfo;
import com.lxw.framework.domain.course.ext.TeachplanNode;
import com.lxw.framework.domain.course.request.CourseListRequest;
import com.lxw.framework.domain.course.response.CourseCode;
import com.lxw.framework.exception.CustomException;
import com.lxw.framework.model.response.CommonCode;
import com.lxw.framework.model.response.QueryResponseResult;
import com.lxw.framework.model.response.QueryResult;
import com.lxw.framework.model.response.ResponseResult;
import com.lxw.manage.course.dao.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class CourseServiceImpl implements ICourseService{

    @Autowired
    TeachplanMapper teachplanMapper;
    @Autowired
    TeachplanRepository teachplanRepository;
    @Autowired
    CourseBaseRepository courseBaseRepository;
    @Autowired
    CourseMapper courseMapper;
    @Autowired
    CoursePicDao coursePicDao;

    @Override
    public TeachplanNode findTeachplanList(String courseId) {
        TeachplanNode teachplanNode = teachplanMapper.selectList(courseId);
        return teachplanNode;
    }

    @Override
    public ResponseResult addTeachplan(Teachplan teachplan) {
        //先验证数据库中有此courseID
        Optional<CourseBase> byId = courseBaseRepository.findById(teachplan.getCourseid());
        if (!byId.isPresent()){
            throw new CustomException(CourseCode.COURSE_PUBLISH_COURSEIDISNULL);
        }

        //先查询是否有根节点 有 添加节点 没有新建节点
        //通过课程id来查询 父节点为0
        List<Teachplan> teachplanList = teachplanRepository.findByCourseidAndParentid(teachplan.getCourseid(), "0");
        Teachplan rootTeach = null;
        if (teachplanList == null || teachplanList.size() == 0){
            //说明没有根节点 添加根节点
            rootTeach = new Teachplan();
            rootTeach.setCourseid(teachplan.getCourseid());
            rootTeach.setParentid("0");
            rootTeach.setGrade("1");
            rootTeach.setOrderby(1);
            rootTeach.setStatus("1");
            //设置课程名
            rootTeach.setPname(byId.get().getName());
            //保存根节点
            rootTeach = teachplanRepository.save(rootTeach);
        }else {
            //获得teachplan
            rootTeach = teachplanList.get(0);
        }
        //判断是否选择父节点 如果没有选择默认为第二节点
        if (StringUtils.isEmpty(teachplan.getParentid())){
            //使用跟节点
            teachplan.setParentid(rootTeach.getId());
            //等级为2
            teachplan.setGrade("2");
        }else {
            //默认三个等级 如果选了就是第三等级
            //查询父节点是否真实存在
            Optional<Teachplan> byId1 = teachplanRepository.findById(teachplan.getParentid());
            if (!byId1.isPresent()){
                throw new CustomException(CourseCode.COURSE_MEDIS_PARENTNULL);
            }
            Teachplan teachplan1 = byId1.get();
            teachplan.setGrade(String.valueOf(Integer.parseInt(teachplan1.getGrade())+1));
        }
        //保存信息
        teachplanRepository.save(teachplan);

        return new ResponseResult(CommonCode.SUCCESS);
    }

    @Override
    public QueryResponseResult findCourseList(Integer page, Integer size, CourseListRequest courseListRequest) {

        //校验数据真实性 TODO
        if (page < 0){
            page = 0;
        }
        if (size <= 0){
            size = 20;
        }
        //分页查询
        PageHelper.startPage(page,size);
        //查询所有的课程
        List<CourseInfo> list = courseMapper.findCourseList(courseListRequest);
        PageInfo<CourseInfo> pageInfo = new PageInfo<>(list);
        QueryResult<CourseInfo> courseInfoQueryResult = new QueryResult<>();
        courseInfoQueryResult.setList(pageInfo.getList());
        courseInfoQueryResult.setTotal(pageInfo.getTotal());

        QueryResponseResult result = new QueryResponseResult(CommonCode.SUCCESS,courseInfoQueryResult);

        return result;
    }

    @Override
    public Teachplan findTeachplanById(String id) {


        Optional<Teachplan> byId = teachplanRepository.findById(id);
        if (!byId.isPresent()){
           throw new CustomException(CommonCode.FAIL);
        }
        Teachplan teachplan = byId.get();
        //判断是否是2级节点，如果是的话设置父节点为null
        String grade = teachplan.getGrade();
        if ("2".equals(grade)){
            teachplan.setParentid(null);
        }


        return teachplan;
    }

    @Override
    public ResponseResult editTeachplan(Teachplan teachplan) {
        //先验证数据库中有此courseID
        Optional<CourseBase> byId = courseBaseRepository.findById(teachplan.getCourseid());
        if (!byId.isPresent()){
            throw new CustomException(CourseCode.COURSE_PUBLISH_COURSEIDISNULL);
        }
        //父节点为null 不保存啊 不更新
        //teachplan.setParentid(null);
        //先查询 在设置
        Optional<Teachplan> byId1 = teachplanRepository.findById(teachplan.getId());
        if (!byId1.isPresent()){
            throw new CustomException(CourseCode.COURSE_PUBLISH_COURSEIDISNULL);
        }
        Teachplan teachplan1 = byId1.get();
        teachplan.setParentid(teachplan1.getParentid());

        //如果传过来的值为空 或者null 则不更新
        if (StringUtils.isEmpty(teachplan.getDescription()) || teachplan.getDescription() == null){
            teachplan.setDescription(teachplan1.getDescription());
        }
        //TODO jpa 更新全字段

        //剩下的更新数据
        teachplanRepository.save(teachplan);
        return new ResponseResult(CommonCode.SUCCESS);
    }



    @Transactional
    @Override
    public ResponseResult delTeachplanById(String id) {
        //逻辑问题 如果是三级标题直接删除 如果是二级标题 则删除所有子节点
        Optional<Teachplan> byId = teachplanRepository.findById(id);
        if (!byId.isPresent()){
            //id无效啊
            throw new CustomException(CommonCode.FAIL);
        }
        Teachplan teachplan = byId.get();
        String grade = teachplan.getGrade();
        if ("1".equals(grade)){
            //如果是一级标题 需要删除课程信息（非课程计划） 和所有子节点
            //TODO
        }else if ("2".equals(grade)){
            //如果是二级标题 则删除所有子节点
            String pid = teachplan.getId();
            //删除所有子节点 只有三级的情况
            teachplanMapper.delByParentid(pid);
        }
        //删除本身 TODO
        teachplanRepository.deleteById(id);
        ResponseResult responseResult = new ResponseResult(CommonCode.SUCCESS);
        return responseResult;
    }

    @Override
    public ResponseResult addCourseBase(CourseBase courseBase) {

        CourseBase save = courseBaseRepository.save(courseBase);
        ResponseResult responseResult = new ResponseResult(CommonCode.SUCCESS);
        return responseResult;
    }

    @Override
    public CourseBase getCourseFormById(String courseId) {
        Optional<CourseBase> byId = courseBaseRepository.findById(courseId);
        if (byId.isPresent()){
            return byId.get();
        }

        return null;
    }

    @Override
    public ResponseResult updateCoursebase(String courseId, CourseBase courseBase) {
        Optional<CourseBase> byId = courseBaseRepository.findById(courseId);
        if (!byId.isPresent()){
            throw new CustomException(CommonCode.FAIL);
        }
        CourseBase courseBase1 = byId.get();
        //更新字段
        if (courseBase.getName() != null && StringUtils.isNotEmpty(courseBase.getName())){
            courseBase1.setName(courseBase.getName());
        }
        if (courseBase.getUsers() != null && StringUtils.isNotEmpty(courseBase.getUsers())){
            courseBase1.setUsers(courseBase.getUsers());
        }
        if (courseBase.getMt() != null && StringUtils.isNotEmpty(courseBase.getMt())){
            courseBase1.setMt(courseBase.getMt());
        }
        if (courseBase.getSt() != null && StringUtils.isNotEmpty(courseBase.getSt())){
            courseBase1.setSt(courseBase.getSt());
        }
        if (courseBase.getGrade() != null && StringUtils.isNotEmpty(courseBase.getGrade())){
            courseBase1.setGrade(courseBase.getGrade());
        }
        if (courseBase.getStudymodel() != null && StringUtils.isNotEmpty(courseBase.getStudymodel())){
            courseBase1.setStudymodel(courseBase.getStudymodel());
        }
        if (courseBase.getDescription() != null && StringUtils.isNotEmpty(courseBase.getDescription())){
            courseBase1.setDescription(courseBase.getDescription());
        }

        CourseBase save = courseBaseRepository.save(courseBase1);
        ResponseResult responseResult = new ResponseResult(CommonCode.SUCCESS);
        return responseResult;
    }

    @Override
    public CourseBase getCourseBaseById(String courseId) {
        Optional<CourseBase> byId = courseBaseRepository.findById(courseId);
        if (byId.isPresent()){
            return byId.get();
        }
        return null;

    }

    @Override
    public ResponseResult addCoursePic(String courseId, String fileId) {

        CoursePic coursePic = new CoursePic();
        coursePic.setCourseid(courseId);
        coursePic.setPic(fileId);
        CoursePic save = coursePicDao.save(coursePic);

        ResponseResult responseResult = new ResponseResult(CommonCode.SUCCESS);

        return responseResult;
    }

    @Override
    public CoursePic getCoursePicById(String courseId) {

        Optional<CoursePic> byId = coursePicDao.findById(courseId);
        if (byId.isPresent()){
            return byId.get();
        }
        return null;
    }

    @Override
    public ResponseResult delCoursePic(String courseId) {

        coursePicDao.deleteById(courseId);

        return new ResponseResult(CommonCode.SUCCESS);
    }
}


























